using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Management;
using System.Net.NetworkInformation;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using Microsoft.Win32;

namespace WindowsOptimizerUltimate
{
    public partial class MainForm : Form
    {
        // 回收站API声明
        [DllImport("Shell32.dll", CharSet = CharSet.Unicode)]
        static extern uint SHEmptyRecycleBin(IntPtr hwnd, string pszRootPath, RecycleBinFlags dwFlags);

        [Flags]
        enum RecycleBinFlags : uint
        {
            SHERB_NOCONFIRMATION = 0x00000001,
            SHERB_NOPROGRESSUI = 0x00000002,
            SHERB_NOSOUND = 0x00000004
        }

        // 内存释放API
        [DllImport("psapi.dll")]
        private static extern int EmptyWorkingSet(IntPtr hwProc);

        // 进程工作集API
        [DllImport("kernel32.dll")]
        private static extern bool SetProcessWorkingSetSize(IntPtr proc, int min, int max);

        // 系统运行时间API
        [DllImport("kernel32.dll")]
        private static extern uint GetTickCount();

        // 热键注册API
        [DllImport("user32.dll")]
        private static extern bool RegisterHotKey(IntPtr hWnd, int id, uint fsModifiers, uint vk);

        [DllImport("user32.dll")]
        private static extern bool UnregisterHotKey(IntPtr hWnd, int id);

        // 常量定义
        private const string AppName = "WindowsOptimizerUltimate";
        private const string RegistryRunPath = "Software\\Microsoft\\Windows\\CurrentVersion\\Run";

        // 性能计数器
        private PerformanceCounter cpuCounter;
        private PerformanceCounter ramCounter;
        private PerformanceCounter diskCounter;
        private PerformanceCounter networkCounter;
        private PerformanceCounter gpuCounter;

        // UI元素
        private Timer updateTimer;
        private Timer memoryCleanTimer;
        private bool isRunningInBackground = false;
        private Mode currentMode = Mode.Normal;
        private NotifyIcon trayIcon;
        private ContextMenuStrip trayMenu;

        // 颜色方案
        private Color goldColor = Color.FromArgb(255, 215, 0);
        private Color darkBackground = Color.FromArgb(15, 15, 20);
        private Color mediumBackground = Color.FromArgb(25, 25, 30);
        private Color lightBackground = Color.FromArgb(40, 40, 45);

        // 模式枚举
        private enum Mode
        {
            Normal,
            Performance,
            Gaming,
            Storm
        }

        public MainForm()
        {
            InitializeComponent();
            InitializeDarkTheme();
            InitializePerformanceCounters();
            InitializeTrayIcon();
            InitializeHotKeys();
            LoadSettings();
            CheckAutoStart();
            
            // 设置窗体样式
            this.FormBorderStyle = FormBorderStyle.FixedSingle;
            this.MaximizeBox = false;
            this.Text = $"{AppName} - 终极系统优化工具";
            this.Icon = Properties.Resources.app_icon;
            
            // 初始化仪表盘
            InitializeDashboard();
            
            // 启动定时器
            updateTimer = new Timer();
            updateTimer.Interval = 1000;
            updateTimer.Tick += UpdateSystemInfo;
            updateTimer.Start();

            // 内存清理定时器
            memoryCleanTimer = new Timer();
            memoryCleanTimer.Interval = 30000; // 30秒
            memoryCleanTimer.Tick += (s, e) => CleanMemory();
            if (chkAutoMemoryClean.Checked)
                memoryCleanTimer.Start();
        }

        // 初始化深色主题
        private void InitializeDarkTheme()
        {
            this.BackColor = darkBackground;
            
            // 设置控件颜色
            foreach (Control control in this.Controls)
            {
                if (control is Panel panel)
                {
                    panel.BackColor = mediumBackground;
                    foreach (Control subControl in panel.Controls)
                    {
                        ApplyDarkThemeToControl(subControl);
                    }
                }
                else
                {
                    ApplyDarkThemeToControl(control);
                }
            }
            
            // 设置标签颜色
            lblCurrentMode.ForeColor = goldColor;
            lblSystemInfoTitle.ForeColor = goldColor;
            lblUptimeTitle.ForeColor = goldColor;
            
            // 设置按钮样式
            SetButtonStyle(btnPerformanceMode);
            SetButtonStyle(btnGamingMode);
            SetButtonStyle(btnStormMode);
            SetButtonStyle(btnMemoryClean);
            SetButtonStyle(btnCacheClean);
            SetButtonStyle(btnMinimizeToTray);
        }

        // 应用深色主题到控件
        private void ApplyDarkThemeToControl(Control control)
        {
            if (control is Label label)
            {
                label.ForeColor = Color.White;
            }
            else if (control is Button button)
            {
                SetButtonStyle(button);
            }
            else if (control is GroupBox groupBox)
            {
                groupBox.ForeColor = goldColor;
                groupBox.BackColor = mediumBackground;
            }
            else if (control is CheckBox checkBox)
            {
                checkBox.ForeColor = Color.White;
            }
        }

        // 设置按钮样式
        private void SetButtonStyle(Button button)
        {
            button.FlatStyle = FlatStyle.Flat;
            button.FlatAppearance.BorderSize = 1;
            button.FlatAppearance.BorderColor = goldColor;
            button.BackColor = lightBackground;
            button.ForeColor = Color.White;
            
            // 添加悬停效果
            button.MouseEnter += (s, e) => 
            {
                button.BackColor = Color.FromArgb(60, 60, 65);
                button.FlatAppearance.BorderColor = Color.FromArgb(255, 223, 0);
            };
            
            button.MouseLeave += (s, e) => 
            {
                button.BackColor = lightBackground;
                button.FlatAppearance.BorderColor = goldColor;
            };
        }

        // 初始化性能计数器
        private void InitializePerformanceCounters()
        {
            cpuCounter = new PerformanceCounter("Processor", "% Processor Time", "_Total");
            ramCounter = new PerformanceCounter("Memory", "Available MBytes");
            diskCounter = new PerformanceCounter("PhysicalDisk", "% Disk Time", "_Total");
            networkCounter = new PerformanceCounter("Network Interface", "Bytes Total/sec", GetActiveNetworkInterface());
            gpuCounter = new PerformanceCounter("GPU Engine", "Utilization Percentage", "pid=0 luid=0x0");
        }

        // 初始化系统托盘图标
        private void InitializeTrayIcon()
        {
            trayIcon = new NotifyIcon
            {
                Icon = Properties.Resources.app_icon,
                Text = AppName,
                Visible = true
            };

            trayMenu = new ContextMenuStrip();
            trayMenu.BackColor = mediumBackground;
            trayMenu.ForeColor = Color.White;
            
            var showItem = new ToolStripMenuItem("显示主界面", null, (s, e) => ShowMainForm());
            showItem.ForeColor = Color.White;
            showItem.BackColor = mediumBackground;
            
            var exitItem = new ToolStripMenuItem("退出", null, (s, e) => ExitApplication());
            exitItem.ForeColor = Color.White;
            exitItem.BackColor = mediumBackground;
            
            trayMenu.Items.Add(showItem);
            trayMenu.Items.Add(exitItem);
            
            trayIcon.ContextMenuStrip = trayMenu;
            trayIcon.DoubleClick += (s, e) => ShowMainForm();
        }

        // 初始化热键
        private void InitializeHotKeys()
        {
            // 注册Ctrl+Alt+O快捷键打开主界面
            RegisterHotKey(this.Handle, 1, 0x0002 | 0x0001, (uint)Keys.O);
        }

        // 初始化仪表盘
        private void InitializeDashboard()
        {
            // 设置仪表盘样式
            cpuGauge.BackColor = Color.Transparent;
            memoryGauge.BackColor = Color.Transparent;
            diskGauge.BackColor = Color.Transparent;
            networkGauge.BackColor = Color.Transparent;
            gpuGauge.BackColor = Color.Transparent;
            
            cpuGauge.ForeColor = goldColor;
            memoryGauge.ForeColor = goldColor;
            diskGauge.ForeColor = goldColor;
            networkGauge.ForeColor = goldColor;
            gpuGauge.ForeColor = goldColor;
            
            // 设置标签样式
            lblCpuValue.Font = new Font("Segoe UI", 10, FontStyle.Bold);
            lblMemoryValue.Font = new Font("Segoe UI", 10, FontStyle.Bold);
            lblDiskValue.Font = new Font("Segoe UI", 10, FontStyle.Bold);
            lblNetworkValue.Font = new Font("Segoe UI", 10, FontStyle.Bold);
            lblGpuValue.Font = new Font("Segoe UI", 10, FontStyle.Bold);
            
            // 设置系统信息标签
            lblSystemInfo.Text = GetSystemInfo();
            lblSystemInfo.ForeColor = Color.White;
            
            // 设置模式选择按钮样式
            btnPerformanceMode.FlatStyle = FlatStyle.Flat;
            btnGamingMode.FlatStyle = FlatStyle.Flat;
            btnStormMode.FlatStyle = FlatStyle.Flat;
            
            btnPerformanceMode.FlatAppearance.BorderSize = 0;
            btnGamingMode.FlatAppearance.BorderSize = 0;
            btnStormMode.FlatAppearance.BorderSize = 0;
        }

        // 获取活动网络接口
        private string GetActiveNetworkInterface()
        {
            foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces())
            {
                if (nic.OperationalStatus == OperationalStatus.Up && 
                    nic.NetworkInterfaceType != NetworkInterfaceType.Loopback)
                {
                    return nic.Description;
                }
            }
            return "";
        }

        // 更新系统信息
        private void UpdateSystemInfo(object sender, EventArgs e)
        {
            // 更新CPU使用率
            float cpuUsage = cpuCounter.NextValue();
            cpuGauge.Value = (int)cpuUsage;
            lblCpuValue.Text = $"{cpuUsage:0.0}%";
            
            // 更新内存使用率
            float availableMemory = ramCounter.NextValue();
            float totalMemory = GetTotalPhysicalMemory();
            float memoryUsage = 100 - (availableMemory * 100 / totalMemory);
            memoryGauge.Value = (int)memoryUsage;
            lblMemoryValue.Text = $"{memoryUsage:0.0}% ({availableMemory:0} MB 可用)";
            
            // 更新磁盘使用率
            float diskUsage = diskCounter.NextValue();
            diskGauge.Value = (int)diskUsage;
            lblDiskValue.Text = $"{diskUsage:0.0}%";
            
            // 更新网络使用率
            float networkUsage = networkCounter.NextValue() / 1024; // KB/s
            networkGauge.Value = (int)networkUsage;
            lblNetworkValue.Text = $"{networkUsage:0.0} KB/s";
            
            // 更新GPU使用率
            float gpuUsage = gpuCounter.NextValue();
            gpuGauge.Value = (int)gpuUsage;
            lblGpuValue.Text = $"{gpuUsage:0.0}%";
            
            // 更新系统运行时间
            lblUptime.Text = GetSystemUptime();
            
            // 根据当前模式更新UI
            UpdateModeUI();
        }

        // 获取总物理内存
        private float GetTotalPhysicalMemory()
        {
            using (ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT TotalPhysicalMemory FROM Win32_ComputerSystem"))
            {
                foreach (ManagementObject obj in searcher.Get())
                {
                    return (float)(ulong)obj["TotalPhysicalMemory"] / (1024 * 1024); // 转换为MB
                }
            }
            return 0;
        }

        // 获取系统运行时间
        private string GetSystemUptime()
        {
            uint uptime = GetTickCount() / 1000; // 转换为秒
            uint days = uptime / (24 * 3600);
            uptime %= (24 * 3600);
            uint hours = uptime / 3600;
            uptime %= 3600;
            uint minutes = uptime / 60;
            uint seconds = uptime % 60;
            
            return $"{days}天 {hours}小时 {minutes}分 {seconds}秒";
        }

        // 获取系统信息
        private string GetSystemInfo()
        {
            string info = "";
            
            // 获取CPU信息
            using (ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT Name FROM Win32_Processor"))
            {
                foreach (ManagementObject obj in searcher.Get())
                {
                    info += $"CPU: {obj["Name"]}\n";
                    break;
                }
            }
            
            // 获取操作系统信息
            using (ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT Caption, Version FROM Win32_OperatingSystem"))
            {
                foreach (ManagementObject obj in searcher.Get())
                {
                    info += $"系统: {obj["Caption"]} {obj["Version"]}\n";
                    break;
                }
            }
            
            // 获取显卡信息
            using (ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT Name FROM Win32_VideoController"))
            {
                foreach (ManagementObject obj in searcher.Get())
                {
                    info += $"显卡: {obj["Name"]}\n";
                    break;
                }
            }
            
            // 获取内存信息
            using (ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT TotalPhysicalMemory FROM Win32_ComputerSystem"))
            {
                foreach (ManagementObject obj in searcher.Get())
                {
                    double totalMemory = (double)(ulong)obj["TotalPhysicalMemory"] / (1024.0 * 1024 * 1024);
                    info += $"内存: {totalMemory:0.00} GB\n";
                    break;
                }
            }
            
            // 获取磁盘信息
            DriveInfo[] drives = DriveInfo.GetDrives();
            foreach (DriveInfo drive in drives)
            {
                if (drive.IsReady)
                {
                    double totalSize = drive.TotalSize / (1024.0 * 1024 * 1024);
                    double freeSpace = drive.TotalFreeSpace / (1024.0 * 1024 * 1024);
                    info += $"磁盘 {drive.Name}: {totalSize:0.00} GB (可用 {freeSpace:0.00} GB)\n";
                }
            }
            
            return info;
        }

        // 应用性能模式
        private void ApplyPerformanceMode()
        {
            // 1. 调整电源计划为高性能
            SetPowerPlan("8c5e7fda-e8bf-4a96-9a85-a6e23a8c635c"); // 高性能GUID
            
            // 2. 禁用不必要的视觉效果
            RegistryKey key = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Explorer\VisualEffects", true);
            if (key != null)
            {
                key.SetValue("VisualFXSetting", 2, RegistryValueKind.DWord); // 调整为最佳性能
                key.Close();
            }
            
            // 3. 优化虚拟内存
            OptimizeVirtualMemory();
            
            // 4. 禁用不必要的服务
            DisableUnnecessaryServices();
            
            // 5. 清理临时文件
            CleanTempFiles();
            
            // 6. 优化网络设置
            OptimizeNetworkSettings();
            
            // 7. 设置进程优先级
            SetProcessPriority(Process.GetCurrentProcess(), ProcessPriorityClass.High);
            
            currentMode = Mode.Performance;
            UpdateModeUI();
            
            ShowNotification("性能模式已启用！", ToolTipIcon.Info);
        }

        // 应用游戏模式
        private void ApplyGamingMode()
        {
            // 1. 应用性能模式的所有优化
            ApplyPerformanceMode();
            
            // 2. 禁用Windows更新服务
            DisableService("wuauserv"); // Windows Update
            
            // 3. 禁用Windows Defender
            DisableService("WinDefend");
            
            // 4. 禁用Superfetch
            DisableService("SysMain");
            
            // 5. 禁用Windows Search
            DisableService("WSearch");
            
            // 6. 禁用通知中心
            RegistryKey key = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\PushNotifications", true);
            if (key != null)
            {
                key.SetValue("ToastEnabled", 0, RegistryValueKind.DWord);
                key.Close();
            }
            
            // 7. 禁用游戏栏和游戏DVR
            RegistryKey gameDVRKey = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\GameDVR", true);
            if (gameDVRKey != null)
            {
                gameDVRKey.SetValue("AppCaptureEnabled", 0, RegistryValueKind.DWord);
                gameDVRKey.SetValue("AudioCaptureEnabled", 0, RegistryValueKind.DWord);
                gameDVRKey.SetValue("CursorCaptureEnabled", 0, RegistryValueKind.DWord);
                gameDVRKey.Close();
            }
            
            currentMode = Mode.Gaming;
            UpdateModeUI();
            
            ShowNotification("游戏模式已启用！", ToolTipIcon.Info);
        }

        // 应用暴风雨模式
        private void ApplyStormMode()
        {
            // 1. 应用游戏模式的所有优化
            ApplyGamingMode();
            
            // 2. 设置极端的电源计划
            SetPowerPlan("e9a42b02-d5df-448d-aa00-03f14749eb61"); // 终极性能模式GUID
            
            // 3. 禁用所有非必要的服务
            DisableAllNonEssentialServices();
            
            // 4. 设置实时优先级
            SetProcessPriority(Process.GetCurrentProcess(), ProcessPriorityClass.RealTime);
            
            // 5. 禁用所有视觉效果
            RegistryKey key = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Explorer\VisualEffects", true);
            if (key != null)
            {
                key.SetValue("VisualFXSetting", 3, RegistryValueKind.DWord); // 调整为最佳性能
                key.Close();
            }
            
            // 6. 禁用Windows Defender实时保护
            RegistryKey defenderKey = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Policies\Microsoft\Windows Defender", true);
            if (defenderKey == null)
            {
                defenderKey = Registry.LocalMachine.CreateSubKey(@"SOFTWARE\Policies\Microsoft\Windows Defender");
            }
            defenderKey.SetValue("DisableAntiSpyware", 1, RegistryValueKind.DWord);
            defenderKey.Close();
            
            // 7. 禁用系统还原
            DisableSystemRestore();
            
            // 8. 禁用休眠
            DisableHibernation();
            
            currentMode = Mode.Storm;
            UpdateModeUI();
            
            MessageBox.Show("暴风雨模式已启用！系统性能将压榨到极限！", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
        }

        // 设置电源计划
        private void SetPowerPlan(string guid)
        {
            Process.Start("powercfg", $"/s {guid}").WaitForExit();
        }

        // 优化虚拟内存
        private void OptimizeVirtualMemory()
        {
            // 获取物理内存大小
            ulong totalMemory = 0;
            using (ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT TotalPhysicalMemory FROM Win32_ComputerSystem"))
            {
                foreach (ManagementObject obj in searcher.Get())
                {
                    totalMemory = (ulong)obj["TotalPhysicalMemory"];
                    break;
                }
            }
            
            // 设置虚拟内存为物理内存的1.5倍
            ulong initialSize = totalMemory * 3 / 2;
            ulong maximumSize = totalMemory * 2;
            
            // 执行命令设置虚拟内存
            Process.Start("wmic", $"computersystem where name=\"%computername%\" set AutomaticManagedPagefile=false").WaitForExit();
            Process.Start("wmic", $"pagefileset where name=\"C:\\\\pagefile.sys\" set InitialSize={initialSize},MaximumSize={maximumSize}").WaitForExit();
        }

        // 禁用不必要的服务
        private void DisableUnnecessaryServices()
        {
            // 禁用一些常见的不必要服务
            string[] servicesToDisable = new string[]
            {
                "DiagTrack", // 诊断跟踪服务
                "dmwappushservice", // 诊断管理服务
                "lfsvc", // 地理位置服务
                "MapsBroker", // 地图服务
                "NetTcpPortSharing", // TCP端口共享服务
                "RemoteRegistry", // 远程注册表
                "SharedAccess", // Internet连接共享
                "TrkWks", // 分布式链接跟踪客户端
                "WMPNetworkSvc", // Windows Media Player网络共享服务
                "WSearch", // Windows搜索
                "XblAuthManager", // Xbox Live认证管理器
                "XblGameSave", // Xbox Live游戏保存
                "XboxNetApiSvc" // Xbox Live网络服务
            };
            
            foreach (string service in servicesToDisable)
            {
                DisableService(service);
            }
        }

        // 禁用所有非必要服务
        private void DisableAllNonEssentialServices()
        {
            // 获取所有非必要的服务
            using (ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM Win32_Service WHERE StartMode = 'Auto' AND State = 'Running'"))
            {
                foreach (ManagementObject service in searcher.Get())
                {
                    string serviceName = service["Name"].ToString();
                    
                    // 跳过关键服务
                    if (IsCriticalService(serviceName))
                        continue;
                        
                    DisableService(serviceName);
                }
            }
        }

        // 检查是否为关键服务
        private bool IsCriticalService(string serviceName)
        {
            // 定义关键服务列表
            string[] criticalServices = new string[]
            {
                "DcomLaunch",
                "RpcSs",
                "RpcEptMapper",
                "SamSs",
                "LSASS",
                "Winmgmt",
                "EventLog",
                "PlugPlay",
                "LanmanServer",
                "LanmanWorkstation",
                "CryptSvc",
                "Dhcp",
                "Dnscache",
                "NlaSvc",
                "Netlogon",
                "Netman",
                "Nsi",
                "Schedule",
                "SENS",
                "ShellHWDetection",
                "Spooler",
                "Themes",
                "AudioSrv",
                "AudioEndpointBuilder",
                "BFE",
                "MpsSvc",
                "WinDefend",
                "WdiSystemHost",
                "WdiServiceHost",
                "Wcmsvc",
                "W32Time",
                "wuauserv"
            };
            
            return criticalServices.Contains(serviceName);
        }

        // 禁用服务
        private void DisableService(string serviceName)
        {
            try
            {
                using (ManagementObject service = new ManagementObject($"Win32_Service.Name='{serviceName}'"))
                {
                    object[] args = { 4 }; // 禁用
                    service.InvokeMethod("ChangeStartMode", args);
                    
                    object[] stopArgs = { };
                    service.InvokeMethod("StopService", stopArgs);
                }
            }
            catch (Exception ex)
            {
                // 忽略服务不存在的错误
                Debug.WriteLine($"无法禁用服务 {serviceName}: {ex.Message}");
            }
        }

        // 清理临时文件
        private void CleanTempFiles()
        {
            // 清理临时文件夹
            string[] tempFolders = new string[]
            {
                Path.GetTempPath(),
                Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Temp"),
                Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Windows), "Temp"),
                Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Windows), "Prefetch")
            };
            
            foreach (string folder in tempFolders)
            {
                try
                {
                    DirectoryInfo dir = new DirectoryInfo(folder);
                    foreach (FileInfo file in dir.GetFiles())
                    {
                        try
                        {
                            file.Delete();
                        }
                        catch { }
                    }
                    
                    foreach (DirectoryInfo subDir in dir.GetDirectories())
                    {
                        try
                        {
                            subDir.Delete(true);
                        }
                        catch { }
                    }
                }
                catch { }
            }
            
            // 清理回收站
            SHEmptyRecycleBin(IntPtr.Zero, null, RecycleBinFlags.SHERB_NOCONFIRMATION | RecycleBinFlags.SHERB_NOPROGRESSUI | RecycleBinFlags.SHERB_NOSOUND);
        }

        // 优化网络设置
        private void OptimizeNetworkSettings()
        {
            // 优化TCP/IP参数
            RegistryKey tcpipParams = Registry.LocalMachine.OpenSubKey(@"SYSTEM\CurrentControlSet\Services\Tcpip\Parameters", true);
            if (tcpipParams != null)
            {
                tcpipParams.SetValue("Tcp1323Opts", 1, RegistryValueKind.DWord);
                tcpipParams.SetValue("DefaultTTL", 64, RegistryValueKind.DWord);
                tcpipParams.SetValue("EnablePMTUDiscovery", 1, RegistryValueKind.DWord);
                tcpipParams.SetValue("EnablePMTUBHDetect", 0, RegistryValueKind.DWord);
                tcpipParams.SetValue("SackOpts", 1, RegistryValueKind.DWord);
                tcpipParams.SetValue("TcpMaxDupAcks", 2, RegistryValueKind.DWord);
                tcpipParams.Close();
            }
            
            // 禁用QoS数据包调度程序
            RegistryKey qosKey = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Policies\Microsoft\Windows\Psched", true);
            if (qosKey == null)
            {
                qosKey = Registry.LocalMachine.CreateSubKey(@"SOFTWARE\Policies\Microsoft\Windows\Psched");
            }
            qosKey.SetValue("NonBestEffortLimit", 0, RegistryValueKind.DWord);
            qosKey.Close();
            
            // 禁用自动调整窗口大小
            RegistryKey autotuningKey = Registry.LocalMachine.OpenSubKey(@"SYSTEM\CurrentControlSet\Services\Tcpip\Parameters", true);
            if (autotuningKey != null)
            {
                autotuningKey.SetValue("EnableRSS", 1, RegistryValueKind.DWord);
                autotuningKey.SetValue("EnableTCPA", 1, RegistryValueKind.DWord);
                autotuningKey.SetValue("EnableTCPChimney", 1, RegistryValueKind.DWord);
                autotuningKey.Close();
            }
        }

        // 禁用系统还原
        private void DisableSystemRestore()
        {
            RegistryKey systemRestoreKey = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows NT\CurrentVersion\SystemRestore", true);
            if (systemRestoreKey != null)
            {
                systemRestoreKey.SetValue("DisableSR", 1, RegistryValueKind.DWord);
                systemRestoreKey.Close();
            }
            
            // 禁用所有驱动器的系统还原
            Process.Start("vssadmin", "delete shadows /all /quiet").WaitForExit();
        }

        // 禁用休眠
        private void DisableHibernation()
        {
            Process.Start("powercfg", "/h off").WaitForExit();
        }

        // 设置进程优先级
        private void SetProcessPriority(Process process, ProcessPriorityClass priority)
        {
            try
            {
                process.PriorityClass = priority;
            }
            catch { }
        }

        // 清理内存
        private void CleanMemory()
        {
            try
            {
                // 获取所有进程
                Process[] processes = Process.GetProcesses();
                
                // 释放每个进程的工作集
                foreach (Process process in processes)
                {
                    try
                    {
                        if (process.ProcessName != Process.GetCurrentProcess().ProcessName)
                        {
                            EmptyWorkingSet(process.Handle);
                        }
                    }
                    catch { }
                }
                
                // 调用垃圾回收
                GC.Collect();
                GC.WaitForPendingFinalizers();
                
                // 设置进程工作集大小
                SetProcessWorkingSetSize(Process.GetCurrentProcess().Handle, -1, -1);
                
                MessageBox.Show("内存清理完成！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (Exception ex)
            {
                MessageBox.Show($"内存清理失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        // 清理缓存文件
        private void CleanCacheFiles()
        {
            try
            {
                // 清理浏览器缓存
                CleanBrowserCache();
                
                // 清理系统缓存
                CleanSystemCache();
                
                // 清理应用缓存
                CleanAppCache();
                
                MessageBox.Show("缓存清理完成！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (Exception ex)
            {
                MessageBox.Show($"缓存清理失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        // 清理浏览器缓存
        private void CleanBrowserCache()
        {
            // 清理Chrome缓存
            string chromeCache = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), 
                "Google\\Chrome\\User Data\\Default\\Cache");
            if (Directory.Exists(chromeCache))
            {
                Directory.Delete(chromeCache, true);
                Directory.CreateDirectory(chromeCache);
            }
            
            // 清理Edge缓存
            string edgeCache = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), 
                "Microsoft\\Edge\\User Data\\Default\\Cache");
            if (Directory.Exists(edgeCache))
            {
                Directory.Delete(edgeCache, true);
                Directory.CreateDirectory(edgeCache);
            }
            
            // 清理Firefox缓存
            string firefoxCache = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), 
                "Mozilla\\Firefox\\Profiles");
            if (Directory.Exists(firefoxCache))
            {
                foreach (string profileDir in Directory.GetDirectories(firefoxCache))
                {
                    string cacheDir = Path.Combine(profileDir, "cache2");
                    if (Directory.Exists(cacheDir))
                    {
                        Directory.Delete(cacheDir, true);
                        Directory.CreateDirectory(cacheDir);
                    }
                }
            }
        }

        // 清理系统缓存
        private void CleanSystemCache()
        {
            // 清理Windows更新缓存
            string updateCache = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Windows), "SoftwareDistribution\\Download");
            if (Directory.Exists(updateCache))
            {
                Directory.Delete(updateCache, true);
                Directory.CreateDirectory(updateCache);
            }
            
            // 清理缩略图缓存
            string thumbnailCache = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), 
                "Microsoft\\Windows\\Explorer");
            if (Directory.Exists(thumbnailCache))
            {
                foreach (string file in Directory.GetFiles(thumbnailCache, "thumbcache_*.db"))
                {
                    try { File.Delete(file); } catch { }
                }
            }
        }

        // 清理应用缓存
        private void CleanAppCache()
        {
            // 清理Spotify缓存
            string spotifyCache = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), 
                "Spotify\\Data");
            if (Directory.Exists(spotifyCache))
            {
                Directory.Delete(spotifyCache, true);
                Directory.CreateDirectory(spotifyCache);
            }
            
            // 清理微信缓存
            string wechatCache = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), 
                "WeChat Files");
            if (Directory.Exists(wechatCache))
            {
                foreach (string userDir in Directory.GetDirectories(wechatCache))
                {
                    string cacheDir = Path.Combine(userDir, "Cache");
                    if (Directory.Exists(cacheDir))
                    {
                        Directory.Delete(cacheDir, true);
                        Directory.CreateDirectory(cacheDir);
                    }
                }
            }
        }

        // 更新模式UI
        private void UpdateModeUI()
        {
            // 重置所有按钮样式
            btnPerformanceMode.BackColor = lightBackground;
            btnGamingMode.BackColor = lightBackground;
            btnStormMode.BackColor = lightBackground;
            
            // 根据当前模式高亮按钮
            switch (currentMode)
            {
                case Mode.Performance:
                    btnPerformanceMode.BackColor = Color.FromArgb(0, 100, 0);
                    break;
                case Mode.Gaming:
                    btnGamingMode.BackColor = Color.FromArgb(0, 0, 100);
                    break;
                case Mode.Storm:
                    btnStormMode.BackColor = Color.FromArgb(100, 0, 0);
                    break;
            }
            
            // 更新状态标签
            lblCurrentMode.Text = $"当前模式: {currentMode}";
        }

        // 加载设置
        private void LoadSettings()
        {
            // 从注册表加载设置
            RegistryKey key = Registry.CurrentUser.OpenSubKey($"Software\\{AppName}");
            if (key != null)
            {
                object modeValue = key.GetValue("CurrentMode");
                if (modeValue != null)
                {
                    currentMode = (Mode)Enum.Parse(typeof(Mode), modeValue.ToString());
                }
                
                object autoStartValue = key.GetValue("AutoStart");
                if (autoStartValue != null)
                {
                    chkAutoStart.Checked = Convert.ToBoolean(autoStartValue);
                }
                
                key.Close();
            }
        }

        // 保存设置
        private void SaveSettings()
        {
            // 保存设置到注册表
            RegistryKey key = Registry.CurrentUser.CreateSubKey($"Software\\{AppName}");
            if (key != null)
            {
                key.SetValue("CurrentMode", currentMode.ToString());
                key.SetValue("AutoStart", chkAutoStart.Checked);
                key.Close();
            }
        }

        // 检查开机自启动
        private void CheckAutoStart()
        {
            RegistryKey key = Registry.CurrentUser.OpenSubKey(RegistryRunPath, false);
            if (key != null)
            {
                chkAutoStart.Checked = key.GetValue(AppName) != null;
                key.Close();
            }
        }

        // 设置开机自启动
        private void SetAutoStart(bool enable)
        {
            RegistryKey key = Registry.CurrentUser.OpenSubKey(RegistryRunPath, true);
            if (key != null)
            {
                if (enable)
                {
                    key.SetValue(AppName, Application.ExecutablePath);
                }
                else
                {
                    key.DeleteValue(AppName, false);
                }
                key.Close();
            }
        }

        // 显示通知
        private void ShowNotification(string message, ToolTipIcon icon)
        {
            trayIcon.ShowBalloonTip(1000, AppName, message, icon);
        }

        // 显示主窗体
        private void ShowMainForm()
        {
            this.Show();
            this.WindowState = FormWindowState.Normal;
            this.BringToFront();
            isRunningInBackground = false;
        }

        // 退出应用程序
        private void ExitApplication()
        {
            SaveSettings();
            trayIcon.Visible = false;
            Application.Exit();
        }

        // 事件处理方法
        private void btnPerformanceMode_Click(object sender, EventArgs e)
        {
            ApplyPerformanceMode();
        }

        private void btnGamingMode_Click(object sender, EventArgs e)
        {
            ApplyGamingMode();
        }

        private void btnStormMode_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("暴风雨模式将压榨系统性能到极限，可能会影响系统稳定性，是否继续？", 
                "警告", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes)
            {
                ApplyStormMode();
            }
        }

        private void btnMemoryClean_Click(object sender, EventArgs e)
        {
            CleanMemory();
        }

        private void btnCacheClean_Click(object sender, EventArgs e)
        {
            CleanCacheFiles();
        }

        private void chkAutoStart_CheckedChanged(object sender, EventArgs e)
        {
            SetAutoStart(chkAutoStart.Checked);
        }

        private void btnMinimizeToTray_Click(object sender, EventArgs e)
        {
            this.Hide();
            isRunningInBackground = true;
            trayIcon.ShowBalloonTip(1000, "系统优化工具", "程序已最小化到系统托盘", ToolTipIcon.Info);
        }

        private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (e.CloseReason == CloseReason.UserClosing && isRunningInBackground)
            {
                e.Cancel = true;
                this.Hide();
            }
            else
            {
                SaveSettings();
                trayIcon.Visible = false;
            }
        }

        private void MainForm_Resize(object sender, EventArgs e)
        {
            if (this.WindowState == FormWindowState.Minimized)
            {
                this.Hide();
                isRunningInBackground = true;
                trayIcon.ShowBalloonTip(1000, "系统优化工具", "程序已最小化到系统托盘", ToolTipIcon.Info);
            }
        }
    }
}
